package edu.lingnan.timer;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import edu.lingnan.entity.Booking;
import edu.lingnan.entity.Seat;
import edu.lingnan.mapper.LogMapper;
import edu.lingnan.service.BookingService;
import edu.lingnan.service.ClassRoomService;
import edu.lingnan.service.SeatService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Author: lrk
 * @Date: 2022/11/2 下午 12:48
 * @Description:
 */
@Component
@Slf4j
public class YuyueTimer {

    @Resource
    private BookingService bookingService;

    @Resource
    private ClassRoomService classRoomService;

    @Resource
    private SeatService seatService;

    @Scheduled(cron = "0 10 0 * * ? ")
    //@Scheduled(cron = "0 0/1 * * * ?")
    @Transactional
    public void run(){
        List<Booking> list = bookingService.list();
        SimpleDateFormat format = new SimpleDateFormat("yyyy-M-d");
        list.forEach(booking -> {
            try {
                //判断预约是否到期
                Date bookEndTime = format.parse(booking.getBEndTime());
                Date nowDate = new Date();
                if (bookEndTime.getTime() + 24 * 60 * 60 * 1000 < nowDate.getTime()){
                    //预约到期
                    //1.将座位设置成可用
                    Integer seatId = booking.getSeatId();
                    Seat seat = new Seat();
                    seat.setSeatId(seatId).setSeatStatus("1");
                    seatService.update(seat, new LambdaQueryWrapper<Seat>().eq(Seat::getSeatId, seatId));

                    //2.教室座位数+1
                    Seat one = seatService.getOne(new LambdaQueryWrapper<Seat>().eq(Seat::getSeatId, seatId));
                    Integer rId = one.getRId();
                    classRoomService.update()
                            .setSql("r_canables = r_canables + 1")
                            .eq("r_id", rId)
                            .update();

                    //删除预约记录
                    bookingService.remove(new LambdaQueryWrapper<Booking>().eq(Booking::getBId, booking.getBId()));

                }
            } catch (ParseException e) {
                throw new RuntimeException(e);
            }
        });
    }

}
